import { Injectable, Logger, NestMiddleware } from '@nestjs/common';
import { NextFunction, Request, Response } from 'express';

@Injectable()
export class AuthHeaderMiddleware implements NestMiddleware {
  private readonly logger = new Logger(AuthHeaderMiddleware.name);

  use(req: Request, res: Response, next: NextFunction) {
    const authHeader = req.headers.authorization;
    this.logger.debug(`Authorization header: ${authHeader}`);

    if (authHeader) {
      // 检查授权头格式是否正确
      if (!authHeader.startsWith('Bearer ')) {
        this.logger.warn(`Invalid authorization header format: ${authHeader}`);
      } else {
        const token = authHeader.substring(7); // 去掉'Bearer '前缀
        if (!token) {
          this.logger.warn('Authorization header found but token is empty');
        } else {
          this.logger.debug('Authorization token is present');
        }
      }
    } else {
      this.logger.debug('No authorization header found');
    }

    next();
  }
}
